package com.dongnaoedu.rpc.redis.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

/**
 * 接收请求数据
 * 
 * @author Tony
 *
 */
@Component
public class ProviderListener implements MessageListener {
	private final Log log = LogFactory.getLog(getClass());

	@Autowired
	StringRedisTemplate stringRedisTemplate;

	/**
	 * 收到数据以后，解析请求内容
	 */
	@Override
	public void onMessage(Message message, byte[] pattern) {
		log.info(new String(message.getBody()));
		JSONObject request = JSONObject.parseObject(new String(message.getBody()));

		log.info("执行方法" + new String(pattern));
		log.error("未实现: 根据请求内容，去调用相关的方法，并在执行结束后 回消息 给消费者的channel");

		// TODO 如果执行方法，拿到结果？
		JSONObject response = new JSONObject();
		response.put("status", 0L);// 执行状态码？ 0 成功 1方法执行异常 2全局异常?
		response.put("msgId", request.getString("msgId"));
		response.put("result", "xxoo，这是执行结果，成功啦"); // xxoo?
		stringRedisTemplate.convertAndSend(request.getString("consumerChannel"), response.toJSONString());

	}

}
